<template>
  <div>
  <div id="addPlant">
    <el-dialog title="添加植物" :visible.sync="visible" top="0.5rem" :lock-scroll="false" :show-close="false" :close-on-click-modal="false">
      <el-form class="addPlant" ref="plantForm" :model="plant" :rules="rules" label-width="100px">
        <el-form-item>
          <div class="avatarlist" style="display:grid;justify-content:start">
            <el-upload
                class="avatar-uploader"
                name="img"
                :action="uploadURL"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
              <img   v-if="plant.avatar" :src="plant.avatar?plant.avatar:'../../../assets/img/bgImg/plant3.png'"  class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">点击上传植物头像，只能上传jpg/png文件，且不超过1mb</div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="植物名字:" prop="plantName" >
          <el-input v-model="plant.plantName"  placeholder="给植物起个名字" clearable :disabled="false"/>
        </el-form-item>
        <el-form-item label="种类："prop="category" label-width="100px">
          <el-select v-model="plant.categoryId" placeholder="种类" style="width: 100px;right: 200px">
            <el-option
                v-for="item in plantCategoryList"
                :key="item.plantCategoryId"
                :label="item.plantCategoryName"
                :value="item.plantCategoryId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" prop="description">
          <el-input type="textarea" :rows="2" v-model="plant.description" resize="none" maxlength="200" show-word-limit palceholder="备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
      <el-button type="primary" @click="resetForm('plantForm')">取消</el-button>
      <el-button type="primary" @click="submitForm('plantForm')">确定</el-button>
    </span>
    </el-dialog>
  </div>
  </div>
</template>

<script>
import store from "@/store";
import {getProductCategoryList} from "@/api/shop";
;
import {getPlantCategoryList} from "@/api/plantCategory";
export default {
  name: "AddPlant",

  data(){
    return{
      rules: {
        plantName:[{required: true, message: '请输入植物名', trigger: 'change'}],
        //category:[{required: true, message: '请选择植物种类', trigger: 'change'}]
      },
      visible:false,
      uploadURL:'',
      plant:{
        plantId:'',
        plantName:'',
        categoryId:'',
        avatar:'',
        status:'',
        description:'',
        followerNum:'',
        plantAge:'',
        createBy:'',
        createTime:'',
        updateBy:'',
        updateTime:''
      },
      category_str:'',
      plantCategoryList:[]

    }
  },
  created() {
    this.uploadURL = store.state.baseURL+'upload'
    console.log(this.uploadURL)

  },
  methods:{
    format() {
      const nowDate = new Date();
      const date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate(),
      }
      const newmonth = date.month > 9 ? date.month : '0' + date.month
      const day = date.date > 9 ? date.date : '0' + date.date
      this.plant.createTime = date.year + '.' + newmonth + '.' + day

    },
    open (item) {
      this.visible=true
      let user=JSON.parse(localStorage.getItem("userInfo"))
      this.plant.createBy=user.id
      // this.plant.plantId=item.plantId
      // this.plant.plantName=item.plantName
      // this.plant.plantAge=item.plantAge
      // this.plant.categoryId=item.categoryId
      // this.plant.avatar=item.avatar
      // this.plant.description=item.description
      // this.plant.followerNum=item.followerNum
      // this.plant.status=item.status
      // this.plant.createBy=item.createBy
      // this.plant.createTime=item.createTime
      // this.plant.updateBy=item.createBy
      // this.plant.updateTime=item.updateTime
      this.getPlantCategory()
    },
    handleAvatarSuccess(res, file) {//上传头像
      console.log("plant_img",res)
      if(res != null){
        this.plant.avatar = res;
        //this.userInfoObj.head_start = 1;
      }else{
        this.$message.error('上传图片失败');
      }

    },
    beforeAvatarUpload(file) {//判断头像大小
      console.log("before")
      const isJPG = file.type == 'image/png'||file.type=='image/jpg'||file.type=='image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 1;
      // console.log(file);
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/JPEG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!');
      }
      return isJPG && isLt2M;
    },
    submitForm (plantForm) {
      this.$refs.plantForm.validate(valid => {
        if (valid) {
          this.$confirm('确认保存吗？', '是否保存', {
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            lockScroll: false,
            type: 'warning'
          }).then(() => {
            console.log('this.fileList', this.fileList)
            this.$emit('confirmData', this.plant,this.fileList)
            this.resetForm('，plantForm')
          })
        }
      })
    },
    getPlantCategory(){
      getPlantCategoryList().then(res=>{
        //console.log(res)
        this.plantCategoryList=res.records
      })
      //console.log("hesakbuewnla")

    },
    resetForm (plantForm) {
      this.$nextTick(() => {
        this.$refs.plantForm.clearValidate()
      })
      this.item = {}
      this.visible = false
    }
  }
}
</script>

<style scoped>

</style>